package com.weituotian.system.dao.impl;

import com.weituotian.core.result.JsTreeNode;
import com.weituotian.system.dao.IMenuDao;
import com.weituotian.system.dao.mapper.Menu2JsTreeNodeMapper;
import com.weituotian.system.entity.Menu;
import com.weituotian.system.entity.Role;
import com.weituotian.system.entity.vo.MenuVo;
import org.springframework.stereotype.Repository;

import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;

@Repository
public class MenuDao extends BaseDao<Menu, Integer> implements IMenuDao {

    @Override
    protected String getEntityName() {
        return "Menu";
    }

    @Override
    protected String getIdFieldName() {
        return "id";
    }


    @Override
    public List<Menu> findAllMenu() {
        String jpql = "select menu from Menu menu left join fetch menu.resource res";
        Query query = getSession().createQuery(jpql);
        return (List<Menu>) query.getResultList();
    }

    @Override
    public List<JsTreeNode> findJsTreeNodeByPid(Integer pid) {
        String jpql = "select menu,count(child.id) from Menu menu left join menu.children child left join fetch menu.resource where menu.pid=:pid group by menu.id";
        Query query = getSession().createQuery(jpql);
        query.setParameter("pid", pid);
        List list= query.getResultList();

        List<JsTreeNode> nodes = new ArrayList<>();
        for (Object row : list) {
            Object[] cells = (Object[]) row;

            //0是menu,1是数量
            JsTreeNode node = Menu2JsTreeNodeMapper.toJsTreeNode((Menu) cells[0]);
            if ((Long)cells[1]>0) {
                node.setChildren(true);
            }
            nodes.add(node);
        }

        return nodes;
    }

    @Override
    public List<Menu> findRootMenu() {
        String jpql = "select menu from Menu menu left join fetch menu.resource where menu.pid is null ";
        Query query = getSession().createQuery(jpql);
        return query.getResultList();
    }
}
